package com.lineng.service.impl;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lineng.dao.DownTableMapper;
import com.lineng.pojo.DownTable;
import com.lineng.service.DownTableService;
import com.lineng.util.UrlUtil;
import com.lineng.util.VerificationUtil;

@Service
public class DownTableServiceImpl implements DownTableService {

	@Autowired
	DownTableMapper downtableMapper;

	@Autowired
	private HttpServletRequest request;

	public List<DownTable> getDownTable() {

		List<DownTable> downTables = downtableMapper.selectByExample(null);
		if (VerificationUtil.verification(request) == 0) {
			for (int i = 0; i < downTables.size(); i++) {
				if (downTables.get(i).getReader() != null && downTables.get(i).getReader() != 0) {
					int result = downTables.get(i).getReader() + 1;
					downtableMapper.updateDownTableReader(result);
				} else {
					downtableMapper.updateDownTableReader(1);
				}
			}
		}
		return downTables;
	}

	public int insertDownTable(DownTable downtable, String username) {
		if (VerificationUtil.verification(request) == 1) {
			downtable.setDate(new Date());
			downtable.setPeople(username);
			if (downtable.getUrl().startsWith("http")) {
				return downtableMapper.insertSelective(downtable);
			} else {
				downtable.setUrl(UrlUtil.url(downtable.getUrl()));
				return downtableMapper.insertSelective(downtable);
			}
		}
		return 0;

	}

	public int updateDownTable(DownTable downtable, String username) {
		if (VerificationUtil.verification(request) == 1) {
			downtable.setDate(new Date());
			downtable.setPeople(username);
			if (downtable.getUrl().startsWith("http")) {
				return downtableMapper.updateByPrimaryKeySelective(downtable);
			} else {
				downtable.setUrl(UrlUtil.url(downtable.getUrl()));
				return downtableMapper.updateByPrimaryKeySelective(downtable);
			}
		}
		return 0;

	}

	public int deleteDownTable(Integer[] idList) {
		if (VerificationUtil.verification(request) == 1) {
			return downtableMapper.deleteById(idList);
		}
		return 0;
	}

}
